#!/usr/bin/env python
# -*- coding:utf-8 -*-
import jwt
import datetime
from jwt import exceptions
import string
import random
import time

JWT_SALT = 'iv%x6xo7l7_u9bf_u!9#g#m*)*=ej@bek5)(@u3kh*72+unjv='


def create_token(role, user_name, i_ex=1200):
    """
    :param role:角色类型
    :param user_name:  用户名
    :param i_ex: token的过期时间，默认20分钟
    :return:
    """
    payload = {
        'role': role,
        "user_name": user_name,  # 账户名
        "exp": int(time.time()) + i_ex,  # 过期时间
        "iat": int(time.time())  # 签发时间
    }
    result = jwt.encode(payload=payload, key=JWT_SALT, algorithm="HS256")
    return result


def parse_payload(token):
    """
    对token进行和发行校验并获取payload
    :param token:
    :return:
    """
    result = {'status': False, 'data': None, 'error': None}
    try:
        verified_payload = jwt.decode(token, JWT_SALT, algorithms=["HS256"])
        result['status'] = True
        result['data'] = verified_payload
    except exceptions.ExpiredSignatureError:
        result['error'] = 'token已失效'
    except jwt.DecodeError:
        result['error'] = 'token认证失败'
    except jwt.InvalidTokenError:
        result['error'] = '非法的token'
    return result
